<template>
  <div ref="chatContainer" style="overflow: auto;height:100%">
    <div class="row" style="padding: 0.2rem 0.115rem;">
      <div v-for="item in classify" :key="item" class="column" style="padding:0 0.085rem" @click="tap(item)">
        <van-image class="icon" :src="item.iconUrl" mode="scaleToFill" />
        <div class="fz28 mt10">{{ item.name }}</div>
      </div>
    </div>
    <div class="column-s box">
      <div class="row" style="margin-bottom:0.15rem">
        <van-image style="width:0.25rem;height:0.26rem;margin-right:0.18rem;" :src="resource.hot" />
        <div class="fz28 fw700">热门问题</div>
      </div>
      <div v-for="item in hots" :key="item" class="fz28 row" style="color: #7E7E7E;width:100%;padding:0.15rem"
        @click="chooseQuestion(item.name)">
        <div class="flex"> {{ item.name }}</div>
        <van-icon name="arrow" />
      </div>
    </div>
    <div v-for="(item, index) in recordList" :key="index">
      <div class="row-s mt20" v-if="item.type == 'ai'">
        <van-image class="avatar" :src="resource.ai" mode="scaleToFill" />
        <div v-html="item.message" class="fz28 content"></div>
      </div>
      <div class="row-s mt20" v-if="item.type == 'user'">
        <van-image class="avatar" :src="item.avatar" mode="scaleToFill" />
        <div class="fz28 content">{{ item.message }}</div>
      </div>
      <div class="column-e" v-if="item.type == 'person'">
        <div class="row-s mt20">
          <div class="fz28 content colorF" style="background: #476CFF;">{{ item.message }}</div>
          <van-image class="avatar" :src="resource.avatar" mode="scaleToFill" />
        </div>
      </div>
      <div class="column-s box" v-if="item.type == 'classify'">
        <div class="row" style="margin-bottom:0.15rem">
          <div class="fz28 fw700">{{ item.name }}</div>
        </div>
        <div v-for="(child, index) in item.list" :key="index" class="fz28 row"
          style="color: #7E7E7E;width:100%;padding:0.15rem" @click="chooseQuestion(child.name)">
          <div class="flex"> {{ child.name }}</div>
          <van-icon name="arrow" />
        </div>
      </div>
      <div class="mt20" v-if="item.type == 'image'">
        <van-image style="width:100%" :src="item.message" mode="scaleToFill" />
      </div>
    </div>
    <div class=" input fz30 row">
      <input v-model="message" placeholder="请输入问题描述...">
      <van-image style="width:0.8rem;height:0.8rem;margin-left:0.2rem;" :src="resource.send" @click="send" />
    </div>
    <div style="height:1.4rem"></div>
  </div>
</template>
<script setup>
import resource from "@/utils/resource";
// import WebSocket from 'websocket';
import { ref, onMounted, nextTick } from 'vue';
import { classifyList, hotList, classDetail, sendQuestion } from "../api/question";
import {
  Toast,
} from 'vant'
const classify = ref([
]);
const hots = ref([])
const question = ref(['酒店提供哪些服务', '如何下单', '遇到问题如何投诉'])
const chatContainer = ref(null)
const consultRecordId = ref(null)
const hotelCode = ref('800505')

var recordList = ref([{
  'type': 'ai', 'message': 'Hi~，我是智能客服MOMO，有问题可以在线跟我互动，我将竭力为您解答。'
}])
var message = ref()
var socket = ref()
var agentUserId = ref()
var casualUserId = ref()
onMounted(() => {
  scrollToBottom();
  getClassify()
  getHot()
});

function send() {
  if (message.value == null) {
    // Toast.fail({ message: '请先输入问题' });
    return;
  }
  recordList.value.push({ 'type': 'person', 'message': message.value })
  if (socket.value && socket.value.readyState === WebSocket.OPEN) {
    let msg =
    {
      "action": 2,
      "hotelCode": hotelCode.value,
      "chatMsg": {
        "sender": {
          "senderId": casualUserId.value,
          "senderType": 1
        },
        "receiver": {
          "receiverId": agentUserId.value,
          "receiverType": 2
        },
        "consultRecordId": consultRecordId.value,
        "msg": message.value
      }
    }
    socket.value.send(JSON.stringify(msg));
    message.value = null
    scrollToBottom();
    return
  }
  sendQuestion({ consultRecordId: consultRecordId.value, questionContent: message.value, hotelCode: hotelCode.value }).then(res => {
    consultRecordId.value = res.data.consultRecordId
    casualUserId.value = res.data.casualUserId
    // if (res.data.answerContent.indexOf('http') != -1) {
    //   recordList.value.push({ 'type': 'image', 'message': res.data.answerContent })
    // } else {
    var content = res.data.answerContent.replace(/<img/g, '<img style="width:100%;height:auto;"');
    console.log(content)
    recordList.value.push({
      'type': 'ai', 'message': content
    })
    // }
    if (res.data.transferToHumanService == 1) {
      if (res.data.agentUserId) {
        agentUserId.value = res.data.agentUserId
        connectWS()
      }
      else {
        recordList.value.push({
          'type': 'ai', 'message': '暂无客服'
        })
      }
    }
    message.value = null
    scrollToBottom();
  })
}
// function getAi() {
//   recordList.value.push({
//     'type': 'ai', 'message': 'Hi~，我是智能客服MOMO，有问题可以在线跟我互动，我讲竭力为您解答。'
//   })
//   scrollToBottom();
// }

function connectWS() {
  socket.value = new WebSocket("wss://chat.mojyun.com/ws");
  socket.value.onopen = (event) => {
    console.log('WebSocket connection opened.');
    let msg = {
      "action": 1,
      "registerUserId": casualUserId.value,
      "registerUserType": 1,
      "hotelCode": hotelCode.value,
    }
    socket.value.send(JSON.stringify(msg));
    let newuser =
    {
      "action": 2,
      "hotelCode": hotelCode.value,
      "chatMsg": {
        "sender": {
          "senderId": casualUserId.value,
          "senderType": 1
        },
        "receiver": {
          "receiverId": agentUserId.value,
          "receiverType": 2
        },
        "consultRecordId": consultRecordId.value,
        "msg": "newUser"
      }
    }
    socket.value.send(JSON.stringify(newuser));
  };
  socket.value.onmessage = (event) => {
    var data = JSON.parse(event.data)
    recordList.value.push({
      'type': 'user', 'message': data.chatMsg.msg, 'avatar': data.chatMsg.sender.onlineUserDetailDtoRes.hotelLogo
    })
    scrollToBottom();
  };
  socket.value.onerror = (e) => {
    console.log('重连。。。')
    console.log(e)
    connectWS()
  }
  socket.value.onclose = (e) => {
    console.log('关闭。。。。')
    recordList.value.push({
      'type': 'ai', 'message': '由于您长时间未响应,当前会话已结束,如有需要请再次发起'
    })
    scrollToBottom();
    console.log(e)
    // connectWS()
  }
}
function tap(val) {
  if (val.descript) {
    recordList.value.push({ 'type': 'image', 'message': val.descript })
  }
  classDetail({ categoryId: val.id }).then(res => {
    recordList.value.push({
      'type': 'classify', 'name': val.name, 'list': res.data
    })
    scrollToBottom();
  })
}
function chooseQuestion(val) {
  recordList.value.push({ 'type': 'person', 'message': val })
  sendQuestion({ consultRecordId: consultRecordId.value, questionContent: val, hotelCode: hotelCode.value }).then(res => {
    consultRecordId.value = res.data.consultRecordId
    var content = res.data.answerContent.replace(/<img/g, '<img style="width:100%;height:auto;"');
    console.log(content)
    recordList.value.push({
      'type': 'ai', 'message': content
    })
    message.value = null
    scrollToBottom();
  })
  // getAi()
}
const scrollToBottom = () => {
  if (chatContainer.value) {
    console.log(chatContainer.value.scrollHeight)
    nextTick(() => {
      window.scrollTo({
        top: chatContainer.value.scrollHeight,
        behavior: 'smooth'
      })
    })
  }
};
function getClassify() {
  classifyList({ hotelCode: hotelCode.value }).then(res => {
    classify.value = res.data
  })
}

function getHot() {
  hotList({ hotelCode: hotelCode.value }).then(res => {
    hots.value = res.data
  })
}



</script>
<style scoped>
.icon {
  width: 1.28rem;
  height: 1.28rem;
}

.avatar {
  width: 0.84rem;
  height: 0.84rem;
  margin-left: 0.2rem;
  margin-right: 0.2rem;
}

.content {
  max-width: 5.36rem;
  padding: 0.28rem;
  border-radius: 0.18rem;
  background: #fff;
}

.box {
  width: 6.34rem;
  padding: 0.3rem 0.38rem;
  margin: 0.2rem;
  background: #fff;
  border-radius: 0.2rem;
}

.input {
  position: fixed;
  bottom: 0;
  background: #f3f3f3;
  padding: 0.2rem 0.2rem 0.28rem 0.2rem;
}

.input input {
  border: transparent;
  border-radius: 0.45rem;
  width: 5.71rem;
  background: #fff;
  line-height: 0.8rem;
  padding-left: 0.4rem;
}
</style>